package com.itheima.mp.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mp.enums.UserStatus;
import com.itheima.mp.service.IUserService;
import com.itheima.mp.domain.User;
import com.itheima.mp.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ServiceUserImpl extends ServiceImpl<UserMapper,User> implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public void deductionBalanceById(Long id, int amount) {
        //1、判断用户是否存在
        User user = this.getById(id);
        if(user==null||user.getStatus()== UserStatus.FREEZE)
        {
            throw new RuntimeException("用户有误");
        }
        //2、判读用户的余额是否足够，余额是否大于扣减的金额
        if(user.getBalance()<amount)
        {
            throw new RuntimeException("余额不足");
        }
        //3、扣减余额
        //获取扣减后的最新余额
        int remainBalance = user.getBalance()-amount;

        this.lambdaUpdate()
                .set(User::getBalance,remainBalance)
                //如果账户余额为零，修改账户状态为冻结
                .set(remainBalance==0,User::getStatus,2)
                .eq(User::getId,id)
                .update();
//        userMapper.deductionBalanceById(amount,id);
    }

   /* @Override
    public UserVO queryUserAndAddressById(Long id) {
        //1.查询用户信息
        User user = getById(id);
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        //2.根据用户的id查询其相对于用户的用户地址列表，然后转换为VO列表设置会VO中
        List<Address> addressList = Db.lambdaQuery(Address.class)
                .eq(Address::getUserId,id)
                .list();
        List<AddressVO> addressVOS = BeanUtil.copyToList(addressList, AddressVO.class);
        userVO.setAddresses(addressVOS);
        return userVO;
    }*/
}
